<template>
  <div class="root">
    <div class="main-content2 four-scroll-y">
      <div class="search-options">
        <strong class="field-title">分类：</strong>
        <div class="field-content" :class="{ unfold: !foldField }">
          <tag-group
            v-if="filedTags.length > 0"
            v-model="fieldList"
            :list="filedTags"
            @field-change="tagSateChange"
          />
        </div>
        <div
          class="collapse-btn"
          :class="{ 'collapse-active': !foldField }"
          @click="foldField = !foldField"
        >
          展开<a-icon type="down" class="icon" />
        </div>
      </div>
      <a-divider dashed style="margin: 12px 0;"></a-divider>

      <div class="sort-options">
        <span style="color: #5d637e;">排序：</span>
        <sort-group v-model="sortInfo" :list="sortGroup" @change="sortChange" />
      </div>

      <a-spin
        v-if="tableLoading"
        :spinning="tableLoading"
        size="large"
        class="spin"
      >
      </a-spin>
      <div v-else-if="modelList.length > 0" class="list-content">
        <div class="model-list">
          <video-cell
            v-for="item in modelList"
            :key="`video-cell-${item.caseId}`"
            :cell="item"
            class="model-cell"
            @search-keyword="setKeyword"
            @update-list="searchClick"
          />
        </div>
        <!-- <a-pagination
            v-model="pageIndex"
            class="pagination"
            align="right"
            :page-size.sync="pageSize"
            :default-current="1"
            :total="totalElements"
            show-size-changer
            show-quick-jumper
            show-less-items
            @change="pageChange"
            @showSizeChange="pageSizeChange"
          /> -->
      </div>

      <div v-else class="list-empty">
        <img alt="" src="@/assets/view/empty2.png" /> 暂无数据
      </div>
    </div>
    <div v-if="showToTop" class="to-top-button" @click="totop()"></div>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop, Watch } from 'vue-property-decorator'
import TagGroup from './TagGroup.vue'
import SortGroup from './SortGroup.vue'
import VideoCell from './VideoCell.vue'
import { throttle } from 'lodash'

import { queryCase } from '@/api/plugin'

@Component({
  components: {
    TagGroup,
    SortGroup,
    VideoCell,
  },
})
export default class CaseList extends Vue {
  @Prop() searchInput!: any
  public queryFm: any = {
    type: '',
    whereValue: '',
    orderKey: 'videoCount',
    order: 'desc',
  }
  public pageIndex: number = 1
  public pageSize: number = 10
  public totalElements: number = 0
  public panelList: any = {}
  public modelList: any = []
  public foldField: boolean = true
  public foldClass: boolean = true
  public tableLoading: boolean = false
  public conHeight: any = '100vh'
  public classShow: boolean = true

  public fieldList: any = []
  public filedTags: any = ['经典', '进阶', '入门']
  public classTags: any = []
  public classList: any = []
  public sortGroup: any = [
    {
      name: '观看量',
      value: 'videoCount',
    },
    {
      name: '发布时间',
      value: 'caseDate',
    },
    // {
    //   name:'收藏量',
    //   value:'collect_count',
    // },
  ]
  public sortInfo: any = {
    value: 'videoCount',
    state: 'desc',
  }

  public timeout: any = {}
  private scrollElement: any = null
  // 是否继续加载数据
  private isAvailable: boolean = true
  public showToTop: boolean = false

  public mounted() {
    this.scrollElement = document.querySelector('.main-content2')
    this.scrollElement.addEventListener(
      'scroll',
      throttle(() => this.onScroll(), 500)
    )
  }

  public created() {
    window.scrollTo(0, 0)
    this.fieldList = this.$route.query.field ? [this.$route.query.field] : []
    this.queryFm.field = this.$route.query.field
    this.queryFm.whereValue = this.searchInput
    this.searchClick()

    window.addEventListener('keyup', this.globalKeyUp)
  }

  public beforeDestroy() {
    document.removeEventListener('keyup', this.globalKeyUp)
    this.scrollElement.removeEventListener(
      'scroll',
      throttle(() => this.onScroll(), 500)
    )
  }

  public async onScroll() {
    const inner = this.scrollElement
    if (inner.scrollTop < 100) {
      this.showToTop = false
    } else {
      this.showToTop = true
    }
    if (
      inner.scrollHeight - inner.scrollTop - 0.4 <= inner.clientHeight &&
      this.isAvailable
    ) {
      this.pageIndex += 1
      const currentList = await this.getCurPageList()
      if (currentList.length > 0) {
        this.modelList.push(...currentList)
      } else {
        this.isAvailable = false
        this.tableLoading = false
      }
    }
  }

  public async getCurPageList() {
    let list: any[] = []
    // this.tableLoading = true
    try {
      const response: any = await queryCase({
        data: {
          ...this.queryFm,
          pageIndex: this.pageIndex,
          pageSize: this.pageSize,
        },
      })
      this.tableLoading = false

      if (response.data.code === 100) {
        list = response.data?.result?.data ?? []
        this.pageIndex = response.data.result.pageIndex
        this.pageSize = response.data.result.pageSize
        this.isAvailable = this.pageIndex < response.data.result.totalPages
        this.totalElements = response.data.result.totalElements
        this.$emit('model-length', this.totalElements)
      } else {
        this.$message.error(response.data.message)
      }
    } catch {
      this.tableLoading = false
    }
    return list
  }

  public totop() {
    this.scrollElement.scrollTo(0, 0)
  }

  public async queryList() {
    this.tableLoading = true
    try {
      const response: any = await queryCase({
        data: {
          ...this.queryFm,
          pageIndex: this.pageIndex,
          pageSize: this.pageSize,
        },
      })
      this.tableLoading = false
      if (response.data.code === 100) {
        this.modelList = response.data.result.data
        this.pageIndex = response.data.result.pageIndex
        this.pageSize = response.data.result.pageSize
        this.totalElements = response.data.result.totalElements
        this.isAvailable = this.pageIndex < response.data.result.totalPages
        this.$emit('case-length', this.totalElements)
      } else {
        this.$message.error(response.data.message)
      }
    } catch {
      this.tableLoading = false
    }
  }

  public searchClick() {
    // 从首页开始查询
    this.pageIndex = 1
    this.pageSize = 10
    this.queryList()
  }

  @Watch('searchInput')
  public smartQuery() {
    console.log('case change')
    this.queryFm.whereValue = this.searchInput
    if (this.timeout) {
      clearTimeout(this.timeout)
    }
    this.timeout = setTimeout(() => this.searchClick(), 300)
  }

  public tagSateChange() {
    if (this.fieldList.includes('all')) {
      this.fieldList = ''
    }
    this.queryFm.field = `${this.fieldList.toString()}`
    // this.queryFm.field = `${this.fieldList.toString()};${this.classList.toString()}`
    this.searchClick()
  }

  public sortChange() {
    this.changeState(this.sortInfo)
  }

  public globalKeyUp($event: any) {
    if ($event.key === 'Enter') {
      setTimeout(() => {
        this.searchClick()
      }, 100)
    }
  }

  public async setKeyword(value: any) {
    // 关键字
    if (this.queryFm.whereValue) {
      if (!this.queryFm.whereValue.split(',').includes(value)) {
        this.queryFm.whereValue = `${this.queryFm.whereValue},${value}`
      }
    } else {
      this.queryFm.whereValue = value
    }
    // this.searchClick()
    this.$emit('search-keyword', this.queryFm.whereValue)
  }

  // public pageChange(page: any, pageSize: any) {
  //   window.scrollTo(0, 0)
  //   this.pageIndex = page
  //   this.pageSize = pageSize
  //   this.queryList()
  // }

  // public pageSizeChange(current: any, size: any) {
  //   window.scrollTo(0, 0)
  //   this.pageIndex = current
  //   this.pageSize = size
  //   this.queryList()
  // }

  public changeState(info: any) {
    this.queryFm.orderKey = info.value
    this.queryFm.order = info.state

    this.searchClick()
  }

  public back() {
    this.$router.go(-1)
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" scoped>
@import '@/styles/scroll-bar';

/deep/
  .ant-collapse
  > .ant-collapse-item
  > .ant-collapse-header
  .ant-collapse-arrow {
  right: 0;
}

.root {
  height: calc(100vh - 268px);
  z-index: 999;

  .to-top-button {
    align-items: center;
    background-color: #525bd0;
    background-image: url('~@/assets/totop.png');
    background-position: center 8px;
    background-repeat: no-repeat;
    background-size: 25px 25px;
    border-radius: 50%;
    bottom: 10%;
    color: #fff;
    cursor: pointer;
    display: flex;
    flex-flow: row nowrap;
    font-size: 28px;
    height: 40px;
    justify-content: center;
    opacity: 0.5;
    position: fixed;
    right: 8%;
    width: 40px;
  }

  .to-top-button:hover {
    opacity: 1;
    transition: all 0.3s;
  }

  .primary {
    color: #6973ff;
  }

  .main-content2 {
    height: calc(100vh - 268px);
    overflow-y: auto;
    padding: 16px 0;
    width: 100%;

    .search-options {
      display: flex;
      padding-left: 32px;
    }

    .sort-options {
      align-items: center;
      display: flex;
      padding: 12px 0 12px 32px;
    }

    .list-content {
      // height: calc(100vh - 268px - 32px - 24px - 32px - 24px);
      height: 100%;

      .model-list {
        background: #fff;
        border-bottom: 1px solid #f5f5f5;
        clear: both;
        // height: calc(100vh - 268px - 32px - 24px - 32px - 24px - 80px);
        min-width: 875px;
        // overflow-y: auto;
        padding-top: 0;
        width: 100%;

        .model-cell {
          background: #fff;
          height: 192px;
          padding: 12px 24px;
          width: 100%;

          &:hover {
            background-color: #f0f3ff;
            cursor: pointer;
          }
        }
      }
    }

    .pagination {
      background: #fff;
      padding: 24px 0;
      text-align: right;
    }

    .list-empty {
      align-items: center;
      background: #fff;
      display: flex;
      flex-direction: column;
      height: calc(100vh - 268px - 32px - 24px - 32px - 24px - 32px - 24px);
      justify-content: center;
      width: 100%;
    }

    .spin {
      background: #fff;
      height: calc(
        100vh - 268px - 32px - 32px - 24px - 32px - 24px - 32px - 24px
      );
      padding-top: 100px;
      width: 100%;
    }

    .tag {
      padding: 20px 6px;

      &:hover {
        background-color: rgba(103, 113, 268, 0.1);
        color: #6973ff;
        cursor: pointer;
      }

      .delete-btn {
        cursor: pointer;
        height: 5px;
        width: 5px;
        // display: none;
      }
    }
  }

  .field-title {
    color: #525bd0;
    line-height: 32px;
    // margin-right:32px;
    min-width: 80px;
  }

  .field-content {
    height: 32px;
    margin-right: 32px;
    overflow: hidden;
    text-align: left;
    text-overflow: ellipsis;
    white-space: nowrap;
    // display: flex;
    width: calc(100% - 180px);
  }

  .unfold {
    height: auto;
  }

  .collapse-btn {
    color: #6773ff;
    cursor: pointer;
    line-height: 32px;

    .icon {
      margin-left: 6px;
      transform: rotate(0);
      transition: transform 0.3s;
    }
  }

  .collapse-active {
    .icon {
      transform: rotate(180deg);
      transition: transform 0.3s;
    }
  }
}
</style>
